<template>
  <div>

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="7" :sm="8">
            <a-form-item label="评估人部门/姓名/手机号" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 0}">
              <a-input placeholder="请输入" v-model="queryParam.queryKey" allowClear></a-input>
            </a-form-item>
          </a-col>

          <a-col :md="5" :sm="8">
            <a-form-item label="被评估人姓名" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 0}">
              <a-input placeholder="请输入" v-model="queryParam.assessedName" allowClear></a-input>
            </a-form-item>
          </a-col>

          <a-col :md="4" :sm="8">
            <a-form-item label="评估状态" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 0}">
              <a-select v-model="queryParam.appraiseStatus">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value=1>已评估</a-select-option>
                <a-select-option value=0>未评估</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="4" :sm="8">
            <a-form-item label="短信通知" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 0}">
              <a-select v-model="queryParam.appraiseNotice">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value=1>已通知</a-select-option>
                <a-select-option value=0>未通知</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
            <a-col :md="4" :sm="24">
              <a-button type="primary" @click="searchQuery">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchReset">重置</a-button>
            </a-col>
          </span>

        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator"  style="margin-top: 5px">
      <a-button @click="modelFormHandle()" type="primary" icon="plus">新增关系</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls">导出关系</a-button>
      <a-button type="primary" icon="import" @click="handleUploadXls">导入关系</a-button>
      <a-button type="primary" @click="handleWeightSettings">权重设置</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDeleteHandle">
            <a-icon type="delete"/>
            <span>删除</span>
          </a-menu-item>
          <a-menu-item key="2" @click="handleSendMessage()">
            <a-icon type="delete"/>
            <span>发送短信</span>
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <a-table
        ref="table"
        size="middle"
        bordered
        :rowKey="(record, index) => index"
        :scroll="{ x: true }"
        :columns="columns"
        :dataSource="dataList"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="tableChangeHandle">

        <span slot="action" slot-scope="text, record">
          <a @click="modelFormHandle(record)">编辑</a>
          <a-divider type="vertical" />


          <a-dropdown>
            <a class="ant-dropdown-link">
              更多 <a-icon type="down" />
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <router-link :to="{ name: 'questionnaire-details', query: { questionId: queryParam.questionId, appraiserPhone: record.appraiserPhone } }">问卷明细</router-link>
              </a-menu-item>
              <a-menu-item>
                <a @click="showAccountPassword(record)">查看密码</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定发送短信通知吗?" @confirm="() => handleSendMessage(record.appraiserPhone)">
                  <a>发送短信</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

    </a-table>

    <account-password ref="accountPassword" v-if="accountPasswordVisible"></account-password>
    <relations-form ref="modelForm" v-if="modelFormVisible" @ok="getList"></relations-form>
    <relations-upload ref="relationsUpload" v-if="relationsUploadVisible" @ok="getList"></relations-upload>
    <weight-settings ref="weightSettings" v-if="weightSettingsVisible"></weight-settings>

  </div>
</template>

<script>
import AccountPassword from './account-password'
import RelationsForm from './relations-form'
import RelationsUpload from './relations-upload'
import WeightSettings from './weight-settings'
import {deleteAction, postAction, postdeleteAction} from '@/api/manage'
import qs from 'qs'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: "relations",
  components: {
    AccountPassword,
    RelationsForm,
    RelationsUpload,
    WeightSettings
  },
  data() {
    return {
      showAppraiseStatus: false,
      loading: false,
      disableMixinActivated: true,
      accountPasswordVisible: false,
      relationsUploadVisible: false,
      weightSettingsVisible: false,
      modelFormVisible: false,
      queryParam: {
        page: 1,
        limit: 10,
        questionId: '',
        appraiseStatus: '',
        appraiseNotice: '',
      },
      dataList: [
        // { username: '张三', mobile: '13569032423', dept: '市场部', number: 35, status: 1, advise: 1 }
      ],
      selectedRowKeys: [],
      selectionRows: [],
      columns: [
        {
          title: '序号',
          dataIndex: '',
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index + 1)
          }
        },
        {
          title: '评估人部门',
          dataIndex: 'deptName',
          align: "center",
        },
        {
          title: '评估人',
          dataIndex: 'appraiserName',
          align: "center",
        },
        {
          title: '评估人手机号',
          dataIndex: 'appraiserPhone',
          align: "center",
        },
        {
          title: '被评估人',
          dataIndex: 'assessedName',
          align: "center",
        },
        {
          title: '问卷数量',
          dataIndex: 'appraiseCount',
          align: "center",
        },
        {
          title: '评估状态',
          dataIndex: 'completeStatus',
          align: "center",
          customRender: function (text) {
            if (text === 0) {
              return <span style="color: #FF8D1A">未评估</span>
            } else if (text === 1) {
              return <span style="color: #87d068">已评估</span>
            } else if (text === 2) {
              return <span style="color: #108ee9">评估中</span>
            }
          }
        },
        {
          title: '短信通知',
          dataIndex: 'appraiseNotice',
          align: "center",
          customRender: function (text) {
            if (text === 0) {
              return '未通知'
            } else if (text === 1) {
              return '已通知'
            }
          }
        },
        {
          title: '完成时间',
          dataIndex: 'appraiseTime',
          align: "center",
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: {customRender: 'action'},
          align: "center",
          width: 170,
          fixed: 'right'
        }
      ],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      url: {
        list: '/appraise/getAppraiseList',
        delete: '/appraise/deleteAppraise',
        sendMsg: '/appraise/sendAnswerMessage'
      }
    }
  },
  watch: {
    $route: {
      handler(to, from) {
        //深度监听，同时也可监听到param参数变化
        this.$nextTick(() => {
          // console.log('to', to)
          // console.log('from', from)
          // if (to.name === 'questionnaire-basic') {
            this.queryParam.questionId = to.query.questionId
            Promise.all([
              this.getList()
            ]).then(() => {
              console.log('this.dataList', this.dataList)
            }).catch(res => {
              console.log('res', res)
            })
          // }
        })
      },
      deep: true,
      // 代表在wacth里声明了这个方法之后立即先去执行handler方法
      immediate: true
    }
  },
  methods: {
    getList() {
      return new Promise((resolve, reject) => {
        this.loading = true
        this.queryParam.page = this.ipagination.current
        this.queryParam.limit = this.ipagination.pageSize
        postAction(this.url.list, this.queryParam).then(res => {
          this.loading = false
          if (!res.success) {
            return this.$message.error({
              content: res.message,
              onClose: () => reject()
            })
          }
          this.dataList = res.result.list
          this.ipagination.total = res.result.total
          resolve()
        }).catch(() => {
          this.loading = false
          reject()
        })
      })
    },
    searchQuery () {
      this.ipagination.current = 1
      this.getList()
      // 点击查询清空列表选中行
      this.onClearSelected()
    },
    onClearSelected () {
      this.selectedRowKeys = [];
      this.selectionRows = [];
    },
    // 多选
    onSelectChange (selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    searchReset() {
      this.queryParam.queryKey = ''
      this.queryParam.assessedName = ''
      this.queryParam.appraiseStatus = ''
      this.queryParam.appraiseNotice = ''
      this.getList()
    },
    reCalculatePage (count) {
      //总数量-count
      let total = this.ipagination.total - count;
      //获取删除后的分页数
      let currentIndex = Math.ceil(total / this.ipagination.pageSize);
      //删除后的分页数<所在当前页
      if (currentIndex < this.ipagination.current) {
        this.ipagination.current = currentIndex;
      }
      console.log('currentIndex', currentIndex)
    },
    tableChangeHandle (pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination)
      this.ipagination = pagination;
      this.getList();
    },
    showAccountPassword(record) {
      this.accountPasswordVisible = true
      this.$nextTick(() => {
        this.$refs.accountPassword.init(record)
      })
    },
    handleUploadXls() {
      this.relationsUploadVisible = true
      this.$nextTick(() => {
        this.$refs.relationsUpload.dataForm.questionId = this.queryParam.questionId
        this.$refs.relationsUpload.init()
      })
    },
    handleWeightSettings() {
      this.weightSettingsVisible = true
      this.$nextTick(() => {
        this.$refs.weightSettings.dataForm.questionId = this.queryParam.questionId
        this.$refs.weightSettings.init()
      })
    },
    handleExportXls () {
      var params = qs.stringify({
        'X-Access-Token': Vue.ls.get(ACCESS_TOKEN),
        ...this.queryParam
      })
      window.location.href = window._CONFIG['domianURL'] + `/appraise/exportAppraise?${ params }`
    },
    // 新增 / 修改
    modelFormHandle (record) {
      this.modelFormVisible = true
      this.$nextTick(() => {
        if (record) {
          this.$refs.modelForm.title = '编辑关系'
          this.$refs.modelForm.dataForm = Object.assign({}, record)
        } else {
          this.$refs.modelForm.title = '新增关系'
          this.$refs.modelForm.dataForm.questionId = this.queryParam.questionId
        }
        this.$refs.modelForm.init()
      })
    },
    batchDeleteHandle: function () {
      if (!this.url.delete) {
        return this.$message.warning("请设置url.delete属性!")
      }
      if (this.selectedRowKeys.length <= 0) {
        return this.$message.warning('请选择一条记录！');
      }
      let idList = []
      for (let i = 0; i < this.selectedRowKeys.length; i++) {
        idList.push(this.dataList[this.selectedRowKeys[i]].appraiserId)
      }
      let params = { questionIdList: [this.queryParam.questionId], appraiserIdList: idList }
      var that = this;
      this.$confirm({
        title: "确认删除",
        content: "是否删除选中数据?",
        onOk: function () {
          that.loading = true;
          postdeleteAction(that.url.delete, params).then((res) => {
            if (res.success) {
              //重新计算分页问题
              that.reCalculatePage(that.selectedRowKeys.length)
              that.$message.success(res.message);
              that.getList();
              that.onClearSelected();
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.loading = false;
          });
        }
      });
    },
    handleSendMessage(appraiserPhone) {
      let phoneList = []
      if (appraiserPhone) {
        phoneList.push(appraiserPhone)
      } else {
        for (let i = 0; i < this.selectedRowKeys.length; i++) {
          phoneList.push(this.dataList[this.selectedRowKeys[i]].appraiserPhone)
        }
      }
      let params = { questionId: this.queryParam.questionId, appraiserPhoneList: phoneList }
      var that = this;
      this.$confirm({
        title: "确认发送",
        content: "是否发送短信?",
        onOk: function () {
          that.$message.info({
            content: '短信发送中...',
            duration: 1,
            onClose: () =>
                postAction(that.url.sendMsg, params).then((res) => {
                  if (res.success) {
                    that.$message.success(res.message);
                    that.getList();
                    that.onClearSelected();
                  } else {
                    that.$message.warning(res.message);
                  }
                })
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
